<?php
namespace WebIM;

class Storage {
    protected $redis;

    const PREFIX = 'webim';

    function __construct($config) {
        $this->redis = \Swoole::getInstance()->redis;
        $this->redis->delete(self::PREFIX.':online');
        $this->config = $config;
    }
    function login($client_id, $info) {
        $this->redis->set(self::PREFIX . ':client:' . $client_id, json_encode($info));
        $this->redis->sAdd(self::PREFIX . ':online', $client_id);
    }
    function logout($client_id) {
        $this->redis->del(self::PREFIX.':client:'.$client_id);
        $this->redis->sRemove(self::PREFIX.':online', $client_id);
    }
    function getOnlineUsers() {
        return $this->redis->sMembers(self::PREFIX . ':online');
    }
    function getUsers($users) {
        $keys = array();
        $ret = array();

        foreach ( $users as $v ) {
            $keys[] = self::PREFIX . ':client:' . $v;
        }

        $info = $this->redis->mget($keys);
        foreach ( $info as $v ) {
            $ret[] = json_decode($v, true);
        }

        return $ret;
    }
    function getUser($userid) { // 获取单个用户信息
        $ret = $this->redis->get(self::PREFIX . ':client:' . $userid);
        $info = json_decode($ret, true);
        return $info;
    }
    function exists($userid) {
        return $this->redis->exists(self::PREFIX . ':client:' . $userid);
    }
    function addHistory($userid, $msg) {
        $info = $this->getUser($userid);

        $log['user'] = $info;
        $log['msg'] = $msg;
        $log['time'] = time();
        $log['type'] = empty($msg['type']) ? '' : $msg['type'];

        table(self::PREFIX.'_history')->put([
            'name' => $info['name'],
            'avatar' => $info['avatar'],
            'msg' => json_encode($msg),
            'type' => empty($msg['type']) ? '' : $msg['type'],
        ]);
    }
    function getHistory($offset=0, $num=100) {
        $data = [];
        $list = table(self::PREFIX.'_history')->gets([
            'limit' => $num,
        ]);
        foreach ( $list as $li ) {
            $result['type'] = $li['type'];
            $result['user'] = array('name' => $li['name'], 'avatar' => $li['avatar']);
            $result['time'] = strtotime($li['addtime']);
            $result['msg'] = json_decode($li['msg'], true);
            $data[] = $result;
        }

        return array_reverse($data);
    }
}
